package concurrent.lock.reentrant;

import org.junit.Test;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock显式的创建锁，加锁和解锁的次数需要相等
 * 必须在finally当中释放锁
 */
public class ReentrantLockTest {

	@Test
	public void test() {

		ReentrantLock lock = new ReentrantLock();

		new Thread(() -> {
			try {
				int i = 1;
				lock.lock();
				System.out.println("第" + i + "次获取锁，锁是：" + lock);
				do {
					try {
						lock.lock();
						System.out.println("第" + (++i) + "次获取锁，锁是：" + lock);
					} catch
					(Exception e) {
						e.printStackTrace();
					} finally {
						lock.unlock();
					}
				} while (i < 10);

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}).start();
	}

}
